package com.ktjiaoyu.crm.web.controller;

import com.ktjiaoyu.crm.entity.Role;
import com.ktjiaoyu.crm.entity.User;
import com.ktjiaoyu.crm.service.IRoleService;
import com.ktjiaoyu.crm.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * @author Administrator
 */
@Controller
public class UserController {
    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @RequestMapping(value = "/dologin")
    public String dologin(String usrName, String usrPassword, HttpServletRequest request, Map<String, Object>map, HttpSession session){
        User user = null;
        try {
            // 此处不再处理登录，由 shiro 进行处理
            AuthenticationToken token = new UsernamePasswordToken(usrName, usrPassword);
            //调用shiro认证
            SecurityUtils.getSubject().login(token);
            user = (User) SecurityUtils.getSubject().getPrincipal();
            //注意此处 session.setAttribute 中 key 的值
            //需要和 Authentication 拦截器session的 key 一致
            session.setAttribute("loginUser", user);
        } catch (IncorrectCredentialsException i){
            i.printStackTrace();
            map.put("message", "密码错误：" + i.getMessage());
            return "login";
        } catch (Exception e){
            map.put("message", e.getMessage());
            return "login";
        }
        return "main";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        //删除
        session.removeAttribute("loginUser");
        //调用登出方法
        SecurityUtils.getSubject().logout();
        return "login";
    }

    @RequestMapping(value = "/user/list")
    public String list(Model model, String usrName,
                       @RequestParam(required = false, defaultValue = "0") Long roleId,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex){
        Sort sort = new Sort(Sort.Direction.ASC, "usrId");
        Pageable pageable = PageRequest.of(pageIndex-1, 5, sort);
        Page<User> userPager = userService.findUsers(usrName, roleId, pageable);
        model.addAttribute("userPager", userPager);
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "user/list";
    }

    @RequestMapping(value = "/user/add")
    public String add(Model model){
        //查询所有角色
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles",roles);

        return "user/add";
    }

    @RequestMapping(value = "/user/save")
    public String save(User user){
        userService.saveUser(user);
        return "redirect:/user/list";//尽量使用重定向，否则刷新页面会重复提交保存操作
    }

    @RequestMapping(value = "/user/edit")
    public String edit(Long usrId, Model model){
        User user = userService.getUser(usrId);
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("user", user);
        model.addAttribute("roles", roles);
        return "user/edit";
    }

    @RequestMapping(value = "/user/del")
    @ResponseBody
    public Map del(Long usrId){
        userService.delUser(usrId);
        Map map = new HashMap();
        map.put("delResult", "true");
        return map;
    }

    @RequestMapping(value = "/role/json")
    @ResponseBody
    public List<Role> findAllRoles(){
        List<Role> list = roleService.findAllRoles();
        return list;
    }


}
